package admin

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gconv"
	apiAdmin "miaoyu/api/backend/admin"
	"miaoyu/internal/enums/userenum"
	modelAdmin "miaoyu/internal/model/admin"
	"miaoyu/internal/model/entity"
	"miaoyu/utility/utils"

	"miaoyu/internal/service"
	function "miaoyu/utility"
)

var Login = new(loginCtl)

type loginCtl struct {
}

/*
Login
author:licx
*/
func (c *loginCtl) Login(ctx context.Context, req *apiAdmin.LoginReq) (res *apiAdmin.LoginRes, err error) {

	_, isLogin := service.Session().IsLogin(ctx)
	if isLogin {
		service.UniResp().UniResp(g.RequestFromCtx(ctx), "您已登陆，无需重复登录！", function.GetRouteByKey("backend/admin/main"))
		//response.UniResp(g.RequestFromCtx(ctx), )
		return
	}
	service.TplResp().BuildTplWithLayout(g.RequestFromCtx(ctx), "login.html").WriteWithExit()
	//response.BuildTpl(g.RequestFromCtx(ctx), "login.html").WriteTpl()
	return
}

// DoLogin  待解决：重复登录，原jwt值仍然有效问题，这个会造成一个账户不断刷token,同时refreshToken刷新时也要注销原token
func (c *loginCtl) DoLogin(ctx context.Context, req *apiAdmin.LoginDoReq) (res *apiAdmin.LoginDoRes, err error) {
	commonJson := service.JsonResp().CommonResp(g.RequestFromCtx(ctx))
	//校验验证码
	capRes := function.CaptchaVerify(req.IdKey, req.Captcha)
	if !capRes {
		commonJson.SetError("验证码输入错误").WriteJsonExit()
		return
	}
	var in modelAdmin.UserLoginInput

	if err = g.RequestFromCtx(ctx).Parse(&in); err != nil {
		return
	}
	//校验用户名密码

	checkUser, checkErr := service.Login().CheckUserPassword(ctx, in)

	if checkErr != nil {
		c.logRecord(ctx, req.UserName, gconv.Int(userenum.Fail))
		commonJson.SetError("用户名或者密码错误").WriteJsonExit()

		return
	}
	res = &apiAdmin.LoginDoRes{}
	//res.Token, res.Expire = service.Auth().LoginHandler(ctx)
	token, expire, genErr := service.Login().DoLogin(ctx, checkUser)

	if genErr != nil {
		commonJson.SetErrorJsonExit("登录验证失败")
	} else {
		res.Token = token
		res.Expire = expire
		c.logRecord(ctx, req.UserName, gconv.Int(userenum.Success))
		commonJson.SetSuccessJsonExit("ok", res)

	}

	return
}
func (c *loginCtl) logRecord(ctx context.Context, username string, state int) {
	r := g.RequestFromCtx(ctx)
	var log entity.MyLogLogin
	log.LoginTime = gtime.Now()
	log.LoginIp = utils.GetClientIp(ctx)
	log.Device = r.UserAgent()
	log.Headers = gconv.String(r.Header)
	log.UserName = username
	log.State = state
	service.Log().LoginLogAdd(ctx, log)
}
func (c *loginCtl) Logout(ctx context.Context, req *apiAdmin.LogoutReq) (res *apiAdmin.LogoutRes, err error) {
	service.Login().DoLogout(ctx)

	service.TplResp().BuildTplWithLayout(g.RequestFromCtx(ctx), "logout.html").WriteWithExit(g.MapStrAny{
		"msg":  "退出成功",
		"path": function.GetRouteByKey("login/login"),
	})
	return
}
